/**
 * 
 */
package a0;

import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

/**
 * @author totyu
 *
 */
public class TestJedis {

    /**
     * @param args
     */
    public static void main(String[] args) {
        testJedis();
        System.out.println("=======================================");
        testJedisSentinel();
    }

    private static void testJedis() {
        // 连接本地的 Redis 服务
        Jedis jedis = new Jedis("192.168.208.141");
        // 如果 Redis 服务设置来密码，需要下面这行，没有就不需要
        jedis.auth("pwd@123");
        System.out.println("连接成功");
        // 查看服务是否运行
        System.out.println("服务正在运行: " + jedis.ping());

        // 设置 redis 字符串数据
        jedis.set("runoobkey", "www.runoob.com");
        // 获取存储的数据并输出
        System.out.println("redis 存储的字符串为: " + jedis.get("runoobkey"));
    }

    private static void testJedisSentinel() {
        Set<String> sentinels = new HashSet<String>();
        sentinels.add("192.168.208.141:26379");
        sentinels.add("192.168.208.142:26379");

        String clusterName = "mymaster";

        JedisSentinelPool jsentinelPool = new JedisSentinelPool(clusterName, sentinels);
        Jedis jedis = null;
        try {
            jedis = jsentinelPool.getResource();
            jedis.set("key", "aaa");
            while (true) {

                try {
                    System.out.println(
                            jedis.getClient().getHost() + ":" + jedis.getClient().getPort() + "@" + jedis.get("key"));
                } catch (Exception e) {
                    System.out.println("getConntion  error,waiting  5s,will try again..." + e.getMessage());
                    Thread.sleep(5000);
                    try {
                        jedis = jsentinelPool.getResource();
                    } catch (Exception e1) {
                        System.out.println("getResource  error2,waiting  more,will try again..." + e.getMessage());
                    }
                }
                Thread.sleep(2000);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        jsentinelPool.close();
    }

}
